package com.android.webserver.tornado;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import com.android.webserver.util.Base64;

import android.util.Log;

public class Response
{
	public final OutputStream				rawOut;
	public final OutputStreamWriter	out;

//	public String										headers;
	public byte[]										RawContent;
	public String										HTMLContent;
	public boolean									isHTML;
	public int											HTTPStatusCode;

	private ArrayList<String>				responseHeadersList;

	private final Socket						socket;

	public Response(Request request) throws IOException
	{
		socket = request.getSocket();
		rawOut = socket.getOutputStream();
		out = new OutputStreamWriter(new BufferedOutputStream(rawOut, 4096),
				"ASCII");
		HTTPStatusCode = HTTP.NOT_FOUND;
		responseHeadersList = new ArrayList<String>();
		isHTML = false;
	}

	public void setHTTPStatusCode(int code)
	{
		HTTPStatusCode = code;
	}

	@SuppressWarnings("unchecked")
	public void setSerializedHeader(String object)
	{
		try
		{
			ByteArrayInputStream in_ = new ByteArrayInputStream(Base64.decode(object));
			ObjectInputStream in;
			in = new ObjectInputStream(in_);
			responseHeadersList.addAll((ArrayList<String>) in.readObject());
			for (String header : responseHeadersList)
				updateIsHTML(header);
		}
		catch (Exception e)
		{
			Log.e("WebServer",
					"Response:setSerializedHeader cannot unserialize headers");
		}
	}

	public void addHeader(String header)
	{
		updateIsHTML(header);
		responseHeadersList.add(header);
	}

	public void modifyHeader(String header)
	{
			String name = header.substring(0, header.indexOf(':'));
			
			for (int i = 0; i < responseHeadersList.size(); i++)
			{
				if (responseHeadersList.get(i).startsWith(name))
				{
					 updateIsHTML(header);
				   responseHeadersList.set(i, header);
				   break;
				}
			}
	}
	public void sendStatus(int code) throws IOException
	{
		StringBuffer status = new StringBuffer(16);
		status.append("HTTP/1.1 ");
		status.append(code);
		status.append(" ");
		status.append(HTTP.getStatusStr(code));
		status.append("\r\n");

		out.write(status.toString());
	}

	public void sendHeaders() throws IOException
	{
		responseHeadersList.add("Date: " + HTTP.formatDate(new Date()));
		responseHeadersList.add("Server: " + Tornado.config.getVersionSig());
		responseHeadersList.add("Connection: close");
		if (responseHeadersList != null)
			for (String header : responseHeadersList)
				out.append(header + "\r\n");
		out.write("\r\n");
		out.flush();
	}

	public void sendContent() throws IOException
	{
		if (HTMLContent != null)
			rawOut.write(HTMLContent.getBytes());
		else
			if (RawContent != null)
				rawOut.write(RawContent);
	}

	public void finishResponse() throws IOException
	{
		out.flush();
		socket.close();
	}
	
	private void updateIsHTML (String header)
	{
		if (header.startsWith("Content-Type: "))
		{
			if (header.equals("Content-Type: text/html"))
				isHTML = true;
			else
				isHTML = false;
		}
	}
}
